#include "COMMON.h"

int main(int argc, const char* argv[])
{
    EnableFile();

    // 从命令行中读取字符串信息
    // 解析
    if(argc < 2 || strcmp(argv[1], "--help") == 0)
    {
        LOG(DEBUG, "Usage error");
        return -1;
    }

    // 创建 socket
    int sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if(sfd == -1)
        LOG(FATAL, "socket create failed");
    
    
    // 初始化服务器地址格式
    struct sockaddr_un SVaddr;
    memset(&SVaddr, 0, sizeof(struct sockaddr_un));
    SVaddr.sun_family = AF_UNIX;
    strncpy(SVaddr.sun_path, SV_SOCK_PATH, sizeof(SVaddr.sun_path) - 1);

    // 初始化客户端地址格式
    struct sockaddr_un CLaddr;
    memset(&CLaddr, 0, sizeof(struct sockaddr_un));
    CLaddr.sun_family = AF_UNIX;
    snprintf(CLaddr.sun_path, sizeof(CLaddr.sun_path), "./client.%ld", (long)getpid());
    
    // 绑定客户端
    if(bind(sfd, (struct sockaddr*)&CLaddr, sizeof(struct sockaddr_un)) == -1)
        LOG(FATAL, "client bind");

    

    int numBytes = 0;
    char buf[BUF_SIZE];
    // 向服务器发送消息
    for(int j = 1; j < argc; j++)
    {
        int msgLen = strlen(argv[j]);
        if(sendto(sfd, argv[j], msgLen, 0, (struct sockaddr*)&SVaddr, sizeof(struct sockaddr_un)) != msgLen)
        {
            LOG(FATAL, "sendto");
            return -1;
        }

        // 从服务器读取消息
        numBytes = recvfrom(sfd, buf, BUF_SIZE, 0, NULL, NULL);
        if(numBytes == -1)
            LOG(DEBUG, "recvfrom");
        buf[numBytes] = '\0';
        printf("Response %d: %s\n", (int)numBytes, buf);
    }
    remove(CLaddr.sun_path);

    LOG(INFO, "client exit");
    return 0;
}